package itman.springcloud.service.impl;


import itman.springcloud.mapper.CartMapper;
import itman.springcloud.mapper.OrderDetailetMapper;
import itman.springcloud.mapper.OrdersMapper;
import itman.springcloud.po.Cart;
import itman.springcloud.po.OrderDetailet;
import itman.springcloud.po.Orders;
import itman.springcloud.service.OrdersService;
import itman.springcloud.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;


    /**
     * 获取自动生成的订单编号， 然后根据用户编号、商家编号从购物车表中查询所有数据，批量添加到订单明细表中， 然后根据用户编号、商家编号删除购物车表中的数据。
     * @param orders
     * @return
     */
    @Override
    public int createOrders(Orders orders) {
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        List<Cart>  cartList= cartMapper.listCart(cart);

        orders.setOrderDate(CommonUtil.getCurrentDateTime());
        ordersMapper.createOrders(orders);
        int orderId =orders.getOrderId();
        OrderDetailet orderDetailet = new OrderDetailet();

        ArrayList<OrderDetailet> list = new ArrayList<>();

        for(Cart c:cartList){
            orderDetailet.setFoodId(c.getFoodId());
            orderDetailet.setOrderId(c.getQuantity());
            orderDetailet.setOrderId(orderId);
            orderDetailet.setQuantity(1);
            list.add(orderDetailet);
        }

        orderDetailetMapper.saveOrderDetailetBatch(list);
        cartMapper.removeCart(cart);
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orders) {
        return ordersMapper.getOrdersById(orders);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }
}
